<?php

include_once 'Param.php';
include_once 'HttpService.php';
include_once 'Sign.php';
include_once 'Parser.php';
class Client
{
    var $url;
    var $partnerID;
    var $partnerKey;
    var $messageFormat = "XML";

    function __construct($url, $partnerID, $partnerKey, $messageFormat){
        $this->url = $url;
        $this->partnerID = $partnerID;
        $this->partnerKey = $partnerKey;
        $this->messageFormat = $messageFormat;
    }

    public function executed($request){
        $param = new Param();
        $param->setPartnerID($this->partnerID);
        $param->setBizData($this->makeBizData($request));
        $param->setServiceType($request->obtainServiceType());
        $param->setPartnerKey($this->partnerKey);

        $signString = $param->getBizData() . $param->getPartnerKey();

        $paramData = array(
			'partnerID'=>$param->getPartnerID(),
			'bizData'=>$param->getBizData(),
			'sign'=>Sign::makeSign($signString),
			'serviceType'=>$param->getServiceType(),
        );
        $headerData = array();

        $paramArray = http_build_query($paramData);
        $response = HttpService::service($paramArray, $headerData, $this->url);
        return $response;
    }

    private function makeBizData($request)
    {
        if (strcasecmp($this->messageFormat, "XML") == 0) {
            $bizData = Parser::coverObject2Xml($request);
        }else {
            $bizData = Parser::coverObject2Json($request);
        }

        return $bizData;
    }
}